package be.vdab.filters;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

/**
 * Servlet Filter implementation class ServletFilter
 */
@WebFilter("*.htm")
public class ServletFilter implements Filter {

    /**
     * Default constructor. 
     */
    public ServletFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		ServletContext context = request.getServletContext();
		HttpServletRequest HSRequest = (HttpServletRequest) request;
		String URL = HSRequest.getRequestURI();
        @SuppressWarnings("unchecked")
        Map <String, Integer> statistiek = (Map<String, Integer>) context.getAttribute("statistiek");
        if (statistiek ==null) {
        	statistiek = new ConcurrentHashMap<String, Integer>();
        	context.setAttribute("statistiek", statistiek);
        }
        if (statistiek.containsKey(URL)) {
        	statistiek.put(URL, statistiek.get(URL) +1);
        } else {
        	statistiek.put(URL, 1);
        }
        context.setAttribute("statistiek", statistiek);  
		chain.doFilter(request, response);
}
	

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
